package com.xin.di.uav.applet.config;

import com.xin.di.uav.common.awt.JwtUtil;
import com.xin.di.uav.common.utils.CheckTokenUtil;
import com.xin.di.uav.common.awt.RepeatSubmit;
import com.xin.di.uav.common.awt.SameUrlDataInterceptor;
import com.xin.di.uav.common.enums.ErrorEnum;
import com.xin.di.uav.common.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

/**
 * @author LTQ
 */
public class JwtInterceptor implements HandlerInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(JwtInterceptor.class);
    @Autowired
    private CheckTokenUtil checkTokenUtil;

    @Autowired
    private SameUrlDataInterceptor sameUrlDataInterceptor;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod handlerMethod)) {
            return true;
        }

        //从 http 请求头中取出 token
        String token = request.getHeader("token");
        if (token == null || "null".equals(token)) {
            throw new BusinessException(ErrorEnum.NO_TOKEN);
        }
        //验证 token
        //验证 token
        JwtUtil.checkSign(token);

        //验证通过后， 这里测试取出JWT中存放的数据
        //获取 token 中的 userId
        String userId = JwtUtil.getUserId(token);
        System.out.println("id : " + userId);
        if (ObjectUtils.isEmpty(userId)) {
            throw new BusinessException(ErrorEnum.NO_TOKEN, "无 token ，请重新登陆");
        }


        //添加防止重复拦截
        Method method = handlerMethod.getMethod();
        RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
        if (annotation != null) {
            if (ObjectUtils.isEmpty(request.getSession().getAttribute(request.getRequestURI()))) {
                request.getSession().setMaxInactiveInterval(annotation.interval());
                request.getSession().setAttribute(request.getRequestURI(), true);
            }

            if (sameUrlDataInterceptor.isRepeatSubmit(request, annotation)) {
                throw new BusinessException(ErrorEnum.REPEATED_SUBMISSION);
            }
        }
        return true;
    }
}

